package org.kfive.nova.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 * User: admin
 * Date: 16-5-15
 * Time: 上午11:52
 * To change this template use File | Settings | File Templates.
 */
public class NioClient {

    private Selector selector;

    public void initClient() throws IOException {
        SocketChannel client = SocketChannel.open();
        client.configureBlocking(false);
        client.connect(new InetSocketAddress(9090));
        selector = Selector.open();
        client.register(this.selector, SelectionKey.OP_CONNECT);
    }

    public void listen() throws IOException {
        while (true){
            this.selector.select();
            Iterator iterator = this.selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = (SelectionKey)iterator.next();
                iterator.remove();
                if(key.isConnectable()){
                    SocketChannel client = (SocketChannel)key.channel();
                    if(client.isConnectionPending()){
                        client.finishConnect();
                    }
                    client.configureBlocking(false);
                    client.write(ByteBuffer.wrap(new String("hello server!").getBytes()));
                    client.register(this.selector,SelectionKey.OP_READ);

                }else if(key.isReadable()){
                    SocketChannel client = (SocketChannel)key.channel();
                    client.configureBlocking(false);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    client.read(byteBuffer);
                    byteBuffer.flip();

                    byte []data =new byte[byteBuffer.remaining()];
                    byteBuffer.get(data);
                    String msg = new String(byteBuffer.array());
                    System.out.println("client receive msg from server:"+msg);
                    byteBuffer.rewind();
                    client.write(byteBuffer);
                }
            }
        }
    }

    public static void main(String[] args) {
        NioClient client = new NioClient();
        try {
            client.initClient();
            client.listen();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
